<template>
    <!-- 人员弹窗 -->
    <a-modal
        centered
        :title="headerTitle"
        :visible.sync="dialogVisible"
        okText="提交"
        @cancel="handleCancel"
        @ok="handleConfirm"
        width="1200px"
    >
        <a-row :gutter="10">
            <a-col v-if="address" :span="24" class="mb20">
                {{ address }}
            </a-col>
            <!-- 侧边栏 -->
            <a-col :span="6" style="border-right: 1px solid #d9d9d9">
                <!-- 公司组织树搜索 -->
                <tree-organization
                    v-if="dialogVisible"
                    ref="treeOrganization"
                    @loader="search"
                    :autoSelect="false"
                    :projectDeptOrgId="projectDeptOrgId"
                    :selectedKeys.sync="selectedKeys"
                    :selectOptions.sync="selectOptions"
                />
            </a-col>
            <!-- 主内容 -->
            <a-col :span="18">
                <a-input-search
                    v-model="nameLike"
                    placeholder="请输入员工名称"
                    class="mb12"
                    :maxLength="30"
                    @search="search"
                ></a-input-search>
                <div>
                    <a-tag
                        class="mb20"
                        v-for="(person, index) in personList"
                        :key="person.id"
                        closable
                        @close="() => handleClose(person, index)"
                        color="#108ee9"
                        >{{ person.name }}</a-tag
                    >
                </div>

                <a-button
                    :disabled="rowSelection.selectedRowKeys.length < 1"
                    type="primary"
                    icon="plus"
                    @click="handleAddMore"
                    >批量添加</a-button
                >
                <!-- 表格 -->
                <s-table
                    v-if="dialogVisible"
                    ref="table"
                    :scroll="{ y: 400 }"
                    tableLayout="fixed"
                    :pageKeys="['pageNumber', 'pageSize']"
                    size="default"
                    :rowKey="(row) => row.id || row.employeeId"
                    :columns="columns"
                    :row-selection="rowSelection"
                    :data="loadData"
                    :alert="true"
                    show-size-changer
                    show-quick-jumper
                    showPagination="auto"
                >
                    <span slot="postPNames" slot-scope="text, record">
                        <div class="ellipsis" :title="filterPostPName(text)">{{ filterPostPName(text) }}</div>
                    </span>
                    <!-- 表格操作栏 -->
                    <span slot="actions" slot-scope="text, record">
                        <template>
                            <a @click="handleSubmit(record)" :disabled="record.isAdd">{{
                                record.isAdd ? '已添加' : '添加'
                            }}</a>
                        </template>
                    </span>
                </s-table>
            </a-col>
        </a-row>
    </a-modal>
</template>

<script>
import { STable } from '@/components' // 表格
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
// import { getOrgsTree } from '@/api/subassembly/TreeSelectOrganization' // api
import cloneDeep from 'lodash.clonedeep' // 深拷贝
import { getOrgEmployeesListBy } from '@/api/commons'
import {
    getOrgsTree,
    getStaffAll,
    getOrgsTreeList,
    getOrgEmployeesList
} from '@/api/subassembly/TreeSelectOrganization'
import { getOneOrgUsers } from '@/api/commons'
export default {
    name: 'updatePerson',
    components: {
        STable,
        TreeOrganization
    },
    props: {
        // 显隐控件
        visible: {
            type: Boolean,
            default() {
                return false
            }
        },
        projectDeptOrgId: {
            type: String,
            default() {
                return ''
            }
        },
        address: {
            type: String,
            default() {
                return ''
            }
        },
        // 表单
        form: {
            type: Object,
            default() {
                return {}
            }
        },
        // 标题
        headerTitle: {
            type: String,
            default() {
                return '编辑入住人'
            }
        },
        // 列表api
        api: {
            type: Object,
            default() {
                return {}
            }
        },
        // 列表api请求axios
        loadList: {
            type: String,
            default() {
                return 'getList'
            }
        },
        persons: {
            type: Array,
            default() {
                return []
            }
        }
    },
    computed: {
        // 树节点api
        apiTree() {
            return { getOrgsTree }
        },
        // 与父组件绑定visible
        dialogVisible: {
            get: function () {
                return this.visible
            },
            set: function (e) {
                this.$emit('update:visible', e)
            }
        },
        // 表格列表请求参数
        args() {
            let args = {}
            // 添加树节点id
            if (this.selectedKeys.length > 0) {
                args.rootOrgId = this.selectedKeys[0]
            }
            // 若表单不为空
            if (Object.keys(this.form)?.length) {
                Object.assign(args, this.form)
            }
            // 若关键词存在
            this.nameLike && (args.nameLike = this.nameLike)
            return args
        }
    },
    data() {
        return {
            queryParam: {},
            nameLike: '',
            selectedKeys: {},
            personList: [],
            // 表格复选框配置
            rowSelection: {
                selectedRowKeys: [],
                onChange(selectedRowKeys, selectedRows) {
                    this.selectedRowKeys = selectedRowKeys
                    this.selectedRows = selectedRows
                },
                getCheckboxProps: (record) => ({
                    props: {
                        disabled: record.isAdd
                    }
                })
            },
            loadData: (parameter) => {
                // if (this.args.orgId) {
                const requestParameters = Object.assign({}, parameter, this.args)

                return getOneOrgUsers(requestParameters).then((res) => {
                    let obj = {}
                    console.log(res)
                    obj.currentPage = requestParameters.pageNumber
                    obj.pageSize = requestParameters.pageSize
                    obj.totalPage = Math.ceil(res.data.total / requestParameters.pageSize)
                    obj.totalSize = res.data.total
                    obj.data = res.data.list

                    console.log(obj)
                    obj.data.forEach((item) => {
                        item.isAdd = false

                        this.personList?.forEach((i, index) => {
                            if (item.userId == i.userId) {
                                item.isAdd = true
                                Object.assign(i, item)
                            }
                        })
                    })

                    console.log(obj)
                    return obj
                })
                // }
            },
            columns: [
                {
                    title: '员工名称',
                    dataIndex: 'name',
                    with: '10%'
                },

                {
                    title: '当前所在岗位',
                    ellipsis: true,
                    dataIndex: 'postPNames',
                    customRender(text, record, index) {
                        return record.postPNames || '-'
                    }
                },

                {
                    title: '操作',
                    dataIndex: 'actions',
                    width: '100px',
                    scopedSlots: { customRender: 'actions' }
                }
            ],
            selectOptions: {}
        }
    },
    methods: {
        getPersion() {
            console.log(this.persons)
            const userIds = []
            this.persons.forEach((item) => {
                userIds.push(item.userId)
            })
            if (userIds.length == 0) return
            getOrgEmployeesListBy({ userIds, delete: true }).then((employees) => {
                this.personList = employees.data
                console.log(this.personList)
            })
        },
        handleClose(removedPerson, index) {
            this.personList.splice(index, 1)
            this.$refs.table.refresh(false)
        },
        handleConfirm() {
            console.log('aa')
            this.handleCancel()
            this.$emit('confirm', this.personList)
        },
        filterPostPName(val) {
            if (val === null) return ''
            return (
                val.reduce &&
                val.reduce((pre, cur) => {
                    return pre === '' ? cur : pre + '、' + cur
                }, '')
            )
        },
        handleAddMore() {
            let list = []
            this.rowSelection.selectedRows.forEach((item) => {
                if (!item.isAdd) {
                    item.isAdd = true
                    list.push(item)
                }
            })
            this.$refs.table.refresh(false)
            list.forEach((item) => {
                this.personList.push(item)
            })

            // this.$emit('confirms', list)
        },
        // 头部搜索
        search() {
            console.log('aaa')
            this.$refs.table.refresh(true)
        },
        handleSubmit(record) {
            let that = this
            record.isAdd = true
            this.$refs.table.refresh(true)
            this.personList.push(record)
            // that.$emit('confirm', record)
        },
        handleCancel() {
            this.dialogVisible = false
        }
    },
    watch: {
        async visible(e) {
            if (e) {
                !this.$refs.treeOrganization &&
                    this.$nextTick(() => {
                        this.$refs.treeOrganization.getList()
                    })
                await this.getPersion()
                this.$nextTick(() => {
                    this.rowSelection.selectedRows = []

                    this.$refs.table.refresh(true)
                })
            } else {
                // 初始化表单
                this.personList = []
            }
        }
    }
}
</script>
<style lang="less" scoped>
.ellipsis {
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    white-space: nowrap;
}
</style>